package com.ts.task;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.ts.mapper.dataOne.BigDataMapper;
import com.ts.model.Bkryyj;
import com.ts.model.JqtJcjmx;
import com.ts.model.ZdryBjhcmx;
import com.ts.model.ZdryYjmx;
import com.ts.utils.HmacSignTypeEnum;
import com.ts.utils.PropertyUtils;
import com.ts.utils.SignBuilder;
import com.ts.utils.StringUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.ts.utils.SignBuilder.genSignUrl;

@Configuration
@EnableScheduling
@ComponentScan
public class BigDataTaskScheduler {

    private final BigDataMapper bigDataMapper;

    @Autowired
    public BigDataTaskScheduler(BigDataMapper bigDataMapper) {
        this.bigDataMapper = bigDataMapper;
    }

    /**
     * 重点人员预警模型定时任务
     */
    //@Scheduled(cron = "40 01 12 * * ?")
    public void zdryyjTask(){
        try {
            int pageNum = 1;
            int pageSize = 1000;
            String ipPort = PropertyUtils.getProp("bigdata_ip_port");
            String token = PropertyUtils.getProp("bigdata_zdryyj_token");
            String url = PropertyUtils.getProp("bigdata_zdryyj_url");

            //1.生成apigs_ca_sign
            Map<String, Object> queryParams = Maps.newHashMap();
            queryParams.put("page_num", pageNum);
            queryParams.put("page_size", pageSize);
            String sign = createSign(token,url,queryParams);

            //2.发送请求，取回结果集，并解析第一组数据入库
            String completeUrl = ipPort + genSignUrl(url, queryParams);
            String responseStr = sendRequest(sign,completeUrl,token);
            analysisZdryyj(responseStr);

            //3.得到总记录数，计算总页数
            JSONObject jsonObject =JSONObject.parseObject(responseStr);
            @SuppressWarnings("unchecked")
            Map<String,Object> data = (Map<String, Object>) jsonObject.get("data");
            @SuppressWarnings("unchecked")
            Map<String,Object> result = (Map<String, Object>) data.get("result");
            int totalSize = (Integer) result.get("total_size");
            //4.根据第一次请求返回的结果，算出最大页码
            int maxPage;
            if(totalSize%pageSize != 0){
                maxPage = totalSize/pageSize + 1;
            }else{
                maxPage = totalSize/pageSize;
            }
            int lastPageSize = totalSize%pageSize;

            if(maxPage > 1){
                for (int i = 2; i <= maxPage; i++) {
                    queryParams.put("page_num", i);
                    if(i == maxPage){
                        queryParams.put("page_size", lastPageSize);
                    }
                    //4.解析结果集并入库
                    sign = createSign(token, url, queryParams);
                    completeUrl = ipPort + genSignUrl(url, queryParams);
                    String rrr = sendRequest(sign,completeUrl,token);
                    analysisZdryyj(rrr);
                    System.out.println("到第【"+i+"】页了！！！！！！！！！！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("重点人员预警模型定时任务结束！");
    }

    /**
     * 近七天接处警模型定时任务
     */
    //@Scheduled(cron = "10 10 * * * ?")
    public void jcjsjmxTask(){
        try {
            String ipPort = PropertyUtils.getProp("bigdata_ip_port");
            String token = PropertyUtils.getProp("bigdata_jcjsjmx_token");
            String url = PropertyUtils.getProp("bigdata_jcjsjmx_url");

            //1.生成apigs_ca_sign
            Map<String, Object> queryParams = Maps.newHashMap();
            Map<String, Object> qp = Maps.newHashMap();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long now = System.currentTimeMillis();
            Date startDate = new Date(now - 1000 * 60 * 60 * 2);
            String starttime = sdf.format(startDate);
            String st = sdf1.format(startDate);
            queryParams.put("bjsj",starttime);
            qp.put("bjsj",st);
            String sign = createSign(token,url,qp);
            //2.发送请求，取回结果集，并解析第一组数据入库
            String completeUrl = ipPort + genSignUrl(url, queryParams);
            String responseStr = sendRequest(sign,completeUrl,token);
            analysisJqtJcjmx(responseStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("近七天接处警模型定时任务结束！");
    }

    /**
     * 重点人员背景核查模型定时任务
     */
    //@Scheduled(cron = "0 43 16 * * ?")
    public void zdrybjhcTask(){
        try {
            int pageNum = 1;
            int pageSize = 1000;
            String ipPort = PropertyUtils.getProp("bigdata_ip_port");
            String token = PropertyUtils.getProp("bigdata_zdrybjhc_token");
            String url = PropertyUtils.getProp("bigdata_zdrybjhc_url");

            //1.生成apigs_ca_sign
            Map<String, Object> queryParams = Maps.newHashMap();
            queryParams.put("page_num", pageNum);
            queryParams.put("page_size", pageSize);
            String sign = createSign(token,url,queryParams);

            //2.发送请求，取回结果集，并解析第一组数据入库
            String completeUrl = ipPort + genSignUrl(url, queryParams);
            String responseStr = sendRequest(sign,completeUrl,token);
            analysisZdryBjhcmx(responseStr);

            //3.得到总记录数，计算总页数
            JSONObject jsonObject =JSONObject.parseObject(responseStr);
            @SuppressWarnings("unchecked")
            Map<String,Object> data = (Map<String, Object>) jsonObject.get("data");
            @SuppressWarnings("unchecked")
            Map<String,Object> result = (Map<String, Object>) data.get("result");
            int totalSize = (Integer) result.get("total_size");
            //4.根据第一次请求返回的结果，算出最大页码
            int maxPage;
            if(totalSize%pageSize != 0){
                maxPage = totalSize/pageSize + 1;
            }else{
                maxPage = totalSize/pageSize;
            }
            int lastPageSize = totalSize%pageSize;

            if(maxPage > 1){
                for (int i = 2; i <= maxPage; i++) {
                    queryParams.put("page_num", i);
                    if(i == maxPage){
                        queryParams.put("page_size", lastPageSize);
                    }
                    //4.解析结果集并入库
                    sign = createSign(token, url, queryParams);
                    completeUrl = ipPort + genSignUrl(url, queryParams);
                    String rrr = sendRequest(sign,completeUrl,token);
                    analysisZdryBjhcmx(rrr);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("重点人员背景核查模型定时任务结束！");
    }

    /**
     * 视频预警_布控人员预警定时任务
     */
    //@Scheduled(cron = "0 * * * * ?")
    public void bkryyjTask(){
        try {
            String ipPort = PropertyUtils.getProp("bigdata_ip_port");
            String token = PropertyUtils.getProp("bigdata_bkryyj_token");
            String url = PropertyUtils.getProp("bigdata_bkryyj_url");

            //1.生成apigs_ca_sign
            Map<String, Object> queryParams = Maps.newHashMap();
            Map<String, Object> qp = Maps.newHashMap();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long now = System.currentTimeMillis();
            Date startDate = new Date(now - 1000 * 60 * 60 * 2);
            Date endDate =  new Date(now);

            String starttime = sdf.format(startDate);
            String endtime = sdf.format(endDate);
            String st = sdf1.format(startDate);
            String et = sdf1.format(endDate);

            queryParams.put("starttime",starttime);
            queryParams.put("endtime",endtime);
            qp.put("starttime",st);
            qp.put("endtime",et);

            String sign = createSign(token,url,qp);

            //2.发送请求，取回结果集，并解析第一组数据入库
            String completeUrl = ipPort + genSignUrl(url, queryParams);
            String responseStr = sendRequest(sign,completeUrl,token);
            analysisBkryyj(responseStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("视频预警_布控人员预警定时任务结束！");
    }

    /**
     * 发送请求，得到返回值
     */
    public String sendRequest(String sign, String completeUrl, String token) throws Exception {

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";

        try{
            httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(completeUrl);
            httpGet.addHeader("Authorization","Bearer " + token);
            httpGet.addHeader("apigs_ca_sign",sign);
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
            httpGet.setConfig(requestConfig);

            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);

        }catch (ClientProtocolException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(null != response){
                response.close();
            }
            if(null != httpClient){
                httpClient.close();
            }
        }
        return result;
    }

    /**
     * 生成sign
     */
    public String createSign(String token , String url , Map<String,Object> queryParams){

        SignBuilder signBuilder = SignBuilder.build()
                .url(genSignUrl(url, queryParams))
                .token(token)
                .signType(HmacSignTypeEnum.HMAC_SHA256);

        return signBuilder.sign();
    }

    /**
     * 解析重点人员预警请求返回值并入库
     */
    public void analysisZdryyj(String responseStr){

        //1.解析json
        JSONObject jsonObject =JSONObject.parseObject(responseStr);
        Map<String,Object> data = (Map<String, Object>) jsonObject.get("data");
        Map<String,Object> result = (Map<String, Object>) data.get("result");
        List<List<String>> values = (List<List<String>>) result.get("values");

        //2.结果入库
        for (List<String> information : values) {
            ZdryYjmx zdryYjmx = new ZdryYjmx();
            zdryYjmx.setId(StringUtil.getUUID());
            zdryYjmx.setRzsj(information.get(0));
            zdryYjmx.setTfsj(information.get(1));
            zdryYjmx.setCsrq(information.get(2));
            zdryYjmx.setBjcrsjhm(information.get(3));
            zdryYjmx.setZdryxlmc(information.get(4));
            zdryYjmx.setCxfrzzsj(information.get(5));
            zdryYjmx.setGxdwmc(information.get(6));
            zdryYjmx.setHzh(information.get(7));
            zdryYjmx.setHjdxz(information.get(8));
            zdryYjmx.setJd(information.get(9));
            zdryYjmx.setGlsj(information.get(10));
            zdryYjmx.setXb(information.get(11));
            zdryYjmx.setZjhm(information.get(12));
            zdryYjmx.setStreet(information.get(13));
            zdryYjmx.setHdgsyys(information.get(14));
            zdryYjmx.setXqj(information.get(15));
            zdryYjmx.setLksj(information.get(16));
            zdryYjmx.setJjsfcgqx(information.get(17));
            zdryYjmx.setTwcl(information.get(18));
            zdryYjmx.setWd(information.get(19));
            zdryYjmx.setXm(information.get(20));
            zdryYjmx.setSffrjz(information.get(21));
            zdryYjmx.setHdgsds(information.get(22));
            zdryYjmx.setGjxwxq(information.get(23));
            zdryYjmx.setQymc(information.get(24));
            zdryYjmx.setFjmc(information.get(25));
            zdryYjmx.setYhsjh(information.get(26));
            zdryYjmx.setMz(information.get(27));
            zdryYjmx.setLxdh(information.get(28));
            zdryYjmx.setDsj(information.get(29));
            zdryYjmx.setHdgssf(information.get(30));
            zdryYjmx.setSfzh(information.get(31));
            zdryYjmx.setZzds(information.get(32));
            zdryYjmx.setZzdq(information.get(33));
            zdryYjmx.setSfjzgl(information.get(34));
            zdryYjmx.setSj(information.get(35));
            zdryYjmx.setJzxm(information.get(36));
            zdryYjmx.setGj(information.get(37));
            zdryYjmx.setFrryjc(information.get(38));
            zdryYjmx.setZdrylbjh(information.get(39));
            zdryYjmx.setJzdxz(information.get(40));
            zdryYjmx.setMc(information.get(41));
            zdryYjmx.setZzdxxzz(information.get(42));
            zdryYjmx.setSq(information.get(43));
            zdryYjmx.setJzwmc(information.get(44));
            zdryYjmx.setZzdshi(information.get(45));
            zdryYjmx.setSmsjh(information.get(46));
            zdryYjmx.setJrczhsq(information.get(47));
            zdryYjmx.setDz(information.get(48));
            zdryYjmx.setSfhbljls(information.get(49));
            zdryYjmx.setScjzjg(information.get(50));
            zdryYjmx.setGjlx(information.get(51));
            zdryYjmx.setXzb(information.get(52));
            zdryYjmx.setYzb(information.get(53));
            bigDataMapper.insertZdryyj(zdryYjmx);
        }
    }

    /**
     * 解析近七天接处警请求返回值并入库
     */
    public void analysisJqtJcjmx(String responseStr){

        //1.解析json
        JSONObject jsonObject =JSONObject.parseObject(responseStr);
        Map<String,Object> data = (Map<String, Object>) jsonObject.get("data");
        Map<String,Object> result = (Map<String, Object>) data.get("result");
        List<List<String>> values = (List<List<String>>) result.get("values");

        //2.结果入库
        for (List<String> information : values) {
            JqtJcjmx jqtJcjmx = new JqtJcjmx();
            jqtJcjmx.setBjsj(null == information.get(0) || "null".equals(information.get(0))?"":information.get(0));
            jqtJcjmx.setCjsj(null == information.get(1) || "null".equals(information.get(1))?"":information.get(1));
            jqtJcjmx.setCjfksj(null == information.get(2) || "null".equals(information.get(2))?"":information.get(2));
            jqtJcjmx.setDdxcsj(null == information.get(3) || "null".equals(information.get(3))?"":information.get(3));
            jqtJcjmx.setJjsj(null == information.get(4) || "null".equals(information.get(4))?"":information.get(4));
            jqtJcjmx.setRksj(null == information.get(5) || "null".equals(information.get(5))?"":information.get(5));
            jqtJcjmx.setCjsjmc(null == information.get(6) || "null".equals(information.get(6))?"":information.get(6));
            jqtJcjmx.setAjzt(null == information.get(7) || "null".equals(information.get(7))?"":information.get(7));
            jqtJcjmx.setZdj(null == information.get(8) || "null".equals(information.get(8))?"":information.get(8));
            jqtJcjmx.setCjr_xm(null == information.get(9) || "null".equals(information.get(9))?"":information.get(9));
            jqtJcjmx.setLxdh(null == information.get(10) || "null".equals(information.get(10))?"":information.get(10));
            jqtJcjmx.setBjlbmc(null == information.get(11) || "null".equals(information.get(11))?"":information.get(11));
            jqtJcjmx.setXzqhbh(null == information.get(12) || "null".equals(information.get(12))?"":information.get(12));
            jqtJcjmx.setBjr_hjdzqh(null == information.get(13) || "null".equals(information.get(13))?"":information.get(13));
            jqtJcjmx.setBjxlmc(null == information.get(14) || "null".equals(information.get(14))?"":information.get(14));
            jqtJcjmx.setXzb(null == information.get(15) || "null".equals(information.get(15))?"":information.get(15));
            jqtJcjmx.setBcjjnr(null == information.get(16) || "null".equals(information.get(16))?"":information.get(16));
            jqtJcjmx.setBjrxb(null == information.get(17) || "null".equals(information.get(17))?"":information.get(17));
            jqtJcjmx.setCjxlmc(null == information.get(18) || "null".equals(information.get(18))?"":information.get(18));
            jqtJcjmx.setCjybh(null == information.get(19) || "null".equals(information.get(19))?"":information.get(19));
            jqtJcjmx.setCjfjmc(null == information.get(20) || "null".equals(information.get(20))?"":information.get(20));
            jqtJcjmx.setCjddj(null == information.get(21) || "null".equals(information.get(21))?"":information.get(21));
            jqtJcjmx.setCjdwdm(null == information.get(22) || "null".equals(information.get(22))?"":information.get(22));
            jqtJcjmx.setJjyxm(null == information.get(23) || "null".equals(information.get(23))?"":information.get(23));
            jqtJcjmx.setXsjqxldm(null == information.get(24) || "null".equals(information.get(24))?"":information.get(24));
            jqtJcjmx.setYzb(null == information.get(25) || "null".equals(information.get(25))?"":information.get(25));
            jqtJcjmx.setCjdh(null == information.get(26) || "null".equals(information.get(26))?"":information.get(26));
            jqtJcjmx.setCdcl(null == information.get(27) || "null".equals(information.get(27))?"":information.get(27));
            jqtJcjmx.setCdry(null == information.get(28) || "null".equals(information.get(28))?"":information.get(28));
            jqtJcjmx.setDwmc(null == information.get(29) || "null".equals(information.get(29))?"":information.get(29));
            jqtJcjmx.setFjmc(null == information.get(30) || "null".equals(information.get(30))?"":information.get(30));
            jqtJcjmx.setDdj(null == information.get(31) || "null".equals(information.get(31))?"":information.get(31));
            jqtJcjmx.setJjdwbh(null == information.get(32) || "null".equals(information.get(32))?"":information.get(32));
            jqtJcjmx.setBjnr(null == information.get(33) || "null".equals(information.get(33))?"":information.get(33));
            jqtJcjmx.setBjrxm(null == information.get(34) || "null".equals(information.get(34))?"":information.get(34));
            jqtJcjmx.setSfdz(null == information.get(35) || "null".equals(information.get(35))?"":information.get(35));
            jqtJcjmx.setJjdbh(null == information.get(36) || "null".equals(information.get(36))?"":information.get(36));
            jqtJcjmx.setCjdbh(null == information.get(37) || "null".equals(information.get(37))?"":information.get(37));
            jqtJcjmx.setCjzdj(null == information.get(38) || "null".equals(information.get(38))?"":information.get(38));
            jqtJcjmx.setBjr_gzdw(null == information.get(39) || "null".equals(information.get(39))?"":information.get(39));
            jqtJcjmx.setJjdh(null == information.get(40) || "null".equals(information.get(40))?"":information.get(40));
            jqtJcjmx.setCjdwmc(null == information.get(41) || "null".equals(information.get(41))?"":information.get(41));
            jqtJcjmx.setCjlbmc(null == information.get(42) || "null".equals(information.get(42))?"":information.get(42));
            jqtJcjmx.setBjlxmc(null == information.get(43) || "null".equals(information.get(43))?"":information.get(43));
            jqtJcjmx.setJjybh(null == information.get(44) || "null".equals(information.get(44))?"":information.get(44));
            jqtJcjmx.setBjr_zjhm(null == information.get(45) || "null".equals(information.get(45))?"":information.get(45));
            jqtJcjmx.setBjdh(null == information.get(46) || "null".equals(information.get(46))?"":information.get(46));
            jqtJcjmx.setFknr(null == information.get(47) || "null".equals(information.get(47))?"":information.get(47));
            jqtJcjmx.setCjlxmc(null == information.get(48) || "null".equals(information.get(48))?"":information.get(48));
            jqtJcjmx.setBjr_hjdz(null == information.get(49) || "null".equals(information.get(49))?"":information.get(49));
            jqtJcjmx.setWyh(null == information.get(50) || "null".equals(information.get(50))?"":information.get(50));
            jqtJcjmx.setSjmc(null == information.get(51) || "null".equals(information.get(51))?"":information.get(51));
            bigDataMapper.insertJqtJcj(jqtJcjmx);
        }
    }

    /**
     * 解析重点人员背景核查请求返回值并入库
     */
    public void analysisZdryBjhcmx(String responseStr){

        //1.解析json
        JSONObject jsonObject =JSONObject.parseObject(responseStr);
        Map<String,Object> data = (Map<String, Object>) jsonObject.get("data");
        Map<String,Object> result = (Map<String, Object>) data.get("result");
        List<List<String>> values = (List<List<String>>) result.get("values");

        //2.结果入库
        for (List<String> information : values) {
            ZdryBjhcmx zdryBjhcmx =new ZdryBjhcmx();
            zdryBjhcmx.setDjsj(information.get(0));
            zdryBjhcmx.setZdryxlmc(information.get(1));
            zdryBjhcmx.setXm(information.get(2));
            zdryBjhcmx.setGxdwmc(information.get(3));
            zdryBjhcmx.setCphm(information.get(4));
            zdryBjhcmx.setGzsm(information.get(5));
            zdryBjhcmx.setGj(information.get(6));
            zdryBjhcmx.setRylb(information.get(7));
            zdryBjhcmx.setCysj(information.get(8));
            zdryBjhcmx.setHjdxz(information.get(9));
            zdryBjhcmx.setZdrylbjh(information.get(10));
            zdryBjhcmx.setZdrybh(information.get(11));
            zdryBjhcmx.setGsmc(information.get(12));
            zdryBjhcmx.setHjdpcsmc(information.get(13));
            zdryBjhcmx.setSfzh(information.get(14));
            zdryBjhcmx.setZz(information.get(15));
            zdryBjhcmx.setJlbgsj(information.get(16));
            bigDataMapper.insertZdrybjhc(zdryBjhcmx);
        }
    }

    /**
     * 解析视频预警_布控人员预警请求返回值并入库
     */
    public void analysisBkryyj(String responseStr){

        //1.解析json
        JSONObject jsonObject =JSONObject.parseObject(responseStr);
        Map<String,Object> data = (Map<String, Object>) jsonObject.get("data");
        Map<String,Object> result = (Map<String, Object>) data.get("result");
        List<List<String>> values = (List<List<String>>) result.get("values");

        if(null != values && values.size() > 0){
            for (List<String> information : values) {

                Bkryyj bkryyj = new Bkryyj();
                bkryyj.setBjsj(information.get(0));
                bkryyj.setIndexcode(information.get(1));
                bkryyj.setBkrw(information.get(2));
                bkryyj.setJd(information.get(3));
                bkryyj.setSsqy(information.get(4));
                bkryyj.setDbt(information.get(5));
                bkryyj.setBjuuid(information.get(6));
                bkryyj.setXm(information.get(7));
                bkryyj.setWd(information.get(8));
                bkryyj.setSsmdk(information.get(9));
                bkryyj.setBjdd(information.get(10));
                bkryyj.setBkrwid(information.get(11));
                bkryyj.setZjhm(information.get(12));
                bkryyj.setZpzp(information.get(13));
                bkryyj.setBjybh(information.get(14));
                bkryyj.setBjylx(information.get(15));
                bkryyj.setBjtp(information.get(16));
                bkryyj.setXsd(information.get(17));
                bkryyj.setSfgz(information.get(18));
                bkryyj.setId(information.get(19));
                bigDataMapper.insertBkryyj(bkryyj);
            }
        }
        //2.结果入库

    }

    public static void main(String[] args) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String starttime = sdf.format(new Date(System.currentTimeMillis()-1000*60*60*2));
        String endtime = sdf.format(new Date(System.currentTimeMillis()));
        System.out.println(starttime);
        System.out.println(endtime);
    }
}
